package link.jfire.socket.socketserver.handler.impl;

import java.nio.charset.Charset;
import javax.annotation.Resource;
import link.jfire.baseutil.collection.ByteCache;
import link.jfire.baseutil.simplelog.ConsoleLogFactory;
import link.jfire.baseutil.simplelog.Logger;
import link.jfire.codejson.JsonArray;
import link.jfire.codejson.JsonObject;
import link.jfire.socket.socketserver.bus.BusinessCommand;
import link.jfire.socket.socketserver.bus.CenterSwitch;
import link.jfire.socket.socketserver.handler.EntryHandler;
import link.jfire.socket.socketserver.interceptor.EntryInterceptor;
import link.jfire.socket.socketserver.storage.Entry;

@Resource
public class ServerInfoHandler implements EntryHandler
{
    private Logger       logger  = ConsoleLogFactory.getLogger();
    private Charset      charset = Charset.forName("utf8");
    @Resource
    private CenterSwitch centerSwitch;
    
    @Override
    public byte interestedDataPacketType()
    {
        return BusinessCommand.SERVER_INFO;
    }
    
    @Override
    public void handler(Entry entry)
    {
        ByteCache cache = entry.getBusinessData();
        String command = cache.toString(charset);
        JsonObject jsonObject = new JsonObject();
        switch (command)
        {
            case "all":
                jsonObject.put("handlers", getHandlerNames());
                jsonObject.put("interceptors", getInterceptorNames());
                logger.info(jsonObject.toString());
                break;
            case "handler":
                jsonObject.put("handlers", getHandlerNames());
                break;
            case "interceptor":
                jsonObject.put("interceptors", getInterceptorNames());
                break;
            default:
                break;
        }
        cache.clear().putArray(jsonObject.toString().getBytes(charset));
        cache.startRead(0);
    }
    
    private JsonArray getHandlerNames()
    {
        JsonArray jsonArray = new JsonArray();
        for (EntryHandler handler : centerSwitch.getHandlerList())
        {
            jsonArray.add(handler.getClass().getName());
        }
        return jsonArray;
    }
    
    private JsonArray getInterceptorNames()
    {
        JsonArray jsonArray = new JsonArray();
        for (EntryInterceptor interceptor : centerSwitch.getInterceptorList())
        {
            jsonArray.add(interceptor.getClass().getName());
        }
        return jsonArray;
    }
}
